using MuYue.ORM.Attributes;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace MuYue.ORM
{
    internal class DbORMCache
    {
        private static DbORMCache m_DbOrmCache;
        private static object m_Lock = new object();
        private Dictionary<int, DbTable> cache;
        public static DbORMCache SingltonCreate() {
            if (DbORMCache.m_DbOrmCache == null) {
                lock (DbORMCache.m_Lock) {
                    if (DbORMCache.m_DbOrmCache == null) {
                        return new DbORMCache();
                    }
                }
            }
            return DbORMCache.m_DbOrmCache;
        }
        private DbORMCache() {
            this.cache = new Dictionary<int, DbTable>();
            DbORMCache.m_DbOrmCache = this;
        }
        public bool GetDbTable<T>(out DbTable mapModel) {
            Type typeFromHandle = typeof(T);
            int hashCode = typeFromHandle.GetHashCode();
            if (this.cache.TryGetValue(hashCode, out mapModel)) {
                return false;
            }
            object[] customAttributes = typeFromHandle.GetCustomAttributes(typeof(DbTableAttribute), true);
            string tableName = Configuration.OrmTableNamePrex + ((customAttributes.Length > 0) ? ((DbTableAttribute)customAttributes[0]).TabelName : typeFromHandle.Name);
            mapModel = new DbTable {
                TEntityType = typeFromHandle,
                TableName = tableName
            };
            PropertyInfo[] properties = typeFromHandle.GetProperties();
            PropertyInfo[] array = properties;
            for (int i = 0; i < array.Length; i++) {
                PropertyInfo info = array[i];
                mapModel.AddPropertyInfo(info);
            }
            this.AppenToCache(hashCode, mapModel);
            return true;
        }
        private void AppenToCache(int hash, DbTable mapModel) {
            lock (this.cache) {
                this.cache.Add(hash, mapModel);
            }
        }
    }
}
